//
//  PictureViewController.swift
//  V2ex-Swift
//
//  Created by Jasper on 2/28/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
//import ObjectMapper
import SVProgressHUD
import AVOSCloud

class CircleViewController: RootViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var circleCollection: UICollectionView!
//    var citysObject:datas? // PictureViewController
    var regionArray = [Region]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "论坛"
//        tabBarController?.tabBar.selectedItem?.selectedImage = UIImage(named: "tabbar_forum_selected")
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 40)
        circleCollection.collectionViewLayout = flowLayout
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        regionArray = DataCenter.sharedInstance.commonRegin
        if regionArray.count == 0 {
          requestDatas()
        }
        circleCollection.reloadData()
    }

    func requestDatas() {
        SVProgressHUD.show()
        let query: AVQuery = Region.query()
        query.includeKey(kRegionKeyCity)
        query.order(byAscending: kRegionKeyOrder)
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
           
            if error == nil && objects != nil {
                if let regins = objects as? [Region] {
                    self.regionArray = regins
                    DataCenter.sharedInstance.commonRegin = regins
                    self.circleCollection.reloadData()
                    SVProgressHUD.dismiss()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
        }
    }
    
    // 创建 数据使用
//    func parseDatas() {
//        let path = NSBundle.mainBundle().pathForResource("citys", ofType: "json")
//        if let data = NSData(contentsOfFile: path!) {
//            if let jsonString =  NSString(data: data, encoding: NSUTF8StringEncoding) {
//                citysObject = Mapper<datas>().map(jsonString)
//                print(citysObject)
//                let data = NSData(contentsOfFile: (NSBundle.mainBundle().pathForResource("defaultImg", ofType: "jpg"))!)
//                let file = AVFile(name: "defaultImg.jpg", data: data)
//                file.saveInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in
//                    
//                    let areas = self.citysObject?.data
//                    
//                    var order = 0
//                    for areas in areas! {
//                        
//                        let region = Region()
//                        region.name = areas.name
//                        region.descriptions = areas.description
//                        region.order = order
//                        order += 1
//                        
//                        let cityArray = areas.city
//                        var array = [City]()
//                        for cityModel in cityArray! {
//                            
//                            let city = City()
//                            city.name = cityModel.name
//                            city.descriptions = cityModel.description
//                            city.replyCount = 0
//                            city.topicCount = 0
//                            city.iconImage = file
//                            array.append(city)
//                        }
//                        
//                        AVObject.saveAllInBackground(array, block: { (success: Bool, error: NSError?) in
//                            if success {
//                                region.addUniqueObjectsFromArray(array, forKey: kRegionKeyCity)
//                                region.saveInBackground()
//                            } else {
//                                print(error?.localizedDescription)
//                            }
//                        })
//                    }
//                }
//            }
//        }
//    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let intWidth = (UIScreen.main.bounds.width - 55)/4
        return CGSize(width: intWidth, height: intWidth+29)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    
    //setion 的个人
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return regionArray.count
//        let areas = citysObject?.data
//        return (areas?.count)!
    }
    
    //实现UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回记录数
        
        let region = regionArray[section]
        return region.citys!.count
        
//        let areas = citysObject?.data
//        let cityDic = areas?[section]
//        let cityArray = cityDic?.city
//        return (cityArray?.count)!
    }
    
    
    //实现UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CircleMainCollectionCell", for: indexPath) as! CircleMainCollectionCell
        
//        let areas = citysObject?.data
//        let cityDic = areas?[indexPath.section]
//        let cityArray = cityDic?.city
//        let cityModel = cityArray?[indexPath.row]
        let region = regionArray[(indexPath as NSIndexPath).section]
        let citys = region.citys
        let city = citys![(indexPath as NSIndexPath).row]
        cell.refreshView(city)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        id <NSFetchedResultsSectionInfo> sectionInfo = [self.frc sections][indexPath.section];
//        Item *item = sectionInfo.objects[0];
//        Location *location = item.location;
//        HeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
//            withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
//        headerView.title.text = location.name;
//        return headerView;
        
        let headerVeiw = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCollectionReusableView", for: indexPath) as! HeaderCollectionReusableView
        let region = regionArray[(indexPath as NSIndexPath).section]
        headerVeiw.refreshView(region.name!)
        return headerVeiw
    }

    //实现UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //某个Cell被选择的事件处理
        
    }

    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "CircleListViewController" {
            if let detailScene = segue.destination as? CircleListViewController {
                let cell = sender as! UICollectionViewCell
                if let indexPath = circleCollection.indexPath(for: cell) {
//                    let object = self.citysObject?.data![indexPath.section].city![indexPath.row]
                    let object = regionArray[(indexPath as NSIndexPath).section].citys![(indexPath as NSIndexPath).row]
                    detailScene.city = object
                    AVAnalytics.event("\(object.name!)")
                }
            }
        }
        // CircleViewController
        segue.destination.hidesBottomBarWhenPushed = true
    }
    
}



//class datas:Mappable {
//    var data: [Areas]?
//    required init?(_ map: Map) {
//        
//    }
//    func mapping(map: Map) {
//        data		    <- map["data"]
//    }
//}
//
//
//class Areas: Mappable {
//    var id: String?
//    var name: String?
//    var description: String?
//    var city: [Citys]?
//    
//    required init?(_ map: Map) {
//        
//    }
//    
//    func mapping(map: Map) {
//        id		    <- map["id"]
//        name		<- map["name"]
//        description	<- map["description"]
//        city        <- map["city"]
//    }
//}
//
//
//class Citys: Mappable {
//    var id: String?
//    var name: String?
//    var description: String?
//    var icon: String?
//    
//    required init?(_ map: Map) {
//        
//    }
//    
//    func mapping(map: Map) {
//        id		    <- map["id"]
//        name		<- map["name"]
//        description	<- map["description"]
//        icon        <- map["icon"]
//    }
//}

